package com.lecture.junit.tdd.example;


import java.util.Calendar;
import java.util.concurrent.atomic.AtomicInteger;

public abstract class LoginServiceState {

    AtomicInteger count;

    public void login(LoginServiceInterface context, IAccount acc, String password) {
        if (acc.passwordMatches(password)) {
            if (acc.isLoggedIn()) {
                throw new AccountAlreadyLoggedInException();
            }
            if (acc.isRevoked()) {
                throw  new AccountIsRevokedException();
            }
            if (acc.isPasswordExpired()) {
                throw new AccountPasswordException();
            }
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_YEAR, -45);
            if (acc.getLastSuccessfullLoginDate() != null && 
                calendar.getTime().after(acc.getLastSuccessfullLoginDate())) {
                acc.setRevoked();
                throw new AccountExpiredException();
            }
            acc.setLoggedIn();
            context.setState(acc.getUserName(), new AwaitFirstLoginAttempt());
        } else {
            handlePasswordFail(context, acc);
        }
    }

    protected abstract void handlePasswordFail(LoginServiceInterface context, IAccount acc);
    
}
